package com.yulan.Tree;

/**
 * 236. 二叉树的最近公共祖先
 */
public class LeetCode_236 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return null;
        if(root == p || root == q) return root;

        TreeNode left = lowestCommonAncestor(root.left,p,q);
        TreeNode right = lowestCommonAncestor(root.right,p,q);

        //如果某一边找不到，则返回另一边
        if(left == null)
            return right;
        if(right == null)
            return left;

        //如果两边都找到，则直接返回
        return root;
    }
}
